package org.dinnermate.db;

import java.sql.SQLException;

import net.java.ao.Common;
import net.java.ao.Entity;
import net.java.ao.Query;
import net.java.ao.schema.TableName;

public abstract class AbstractImplementation<T extends Entity>
{
	protected T ao;

	public AbstractImplementation( T ao )
	{
		this.ao = ao;
	}

	@SuppressWarnings("unchecked")
	public boolean equals( Object ob )
	{
		try
		{
			return ao.getID() == ((T) ob).getID();
		}
		catch (Exception e)
		{
			System.err.println(ao.getEntityType().getSimpleName() + " bad cast in equals");
			return false;
		}
	}

	public String toString()
	{
		return ao.getClass().getSimpleName() + " ID " + ao.getID();
	}
	
	protected void deleteMaps() throws SQLException
	{
		MapClass mapClass = ao.getEntityType().getAnnotation(MapClass.class);
		
		if (mapClass != null)
		{
			Class<? extends Entity>[] values = mapClass.value();
			
			for (Class<? extends Entity> value : values)
			{
				deleteMaps(value);
			}
		}
		else
		{
			throw new NoMapClassException();
		}
	}
	
	protected <K extends Entity> void deleteMaps( Class<K> mapClass ) throws SQLException
	{
		deleteMaps(mapClass, "");
	}

	protected <K extends Entity> void deleteMaps( Class<K> mapClass, String colName ) throws SQLException
	{
		String col = "";
		if (colName == "")
		{
			TableName tableName = ao.getEntityType().getAnnotation(TableName.class);
			col = Common.convertDowncaseName(tableName.value()) + "ID";
		}
		else
		{
			col = colName;
		}

		K[] toDelete = DBManager.getEntityManager().find(mapClass, Query.select().where(col + " = ?", ao.getID()));
		DBManager.getEntityManager().delete(toDelete);
	}
}
